// pages/publish/publish.js
Page({
  data: {
    publishType: 'car', // 发布类型：car 或 person
    startDate: '', // 日期选择器起始日期
    // 出发地选项
    departureOptions: ['南关区', '宽城区', '朝阳区', '二道区', '绿园区', '双阳区', '九台区'],
    departureIndex: -1,
    // 目的地选项
    destinationOptions: ['庙香山', '莲花山', '天定山', '松花湖', '北大湖', '万峰', '长白山'],
    destinationIndex: -1,
    formData: {
      departure: '',
      destination: '',
      date: '',
      time: '',
      capacity: '',
      boardCapacity: '', // 可承载板数
      price: '',
      contact: '',
      remark: ''
    }
  },

  onLoad: function (options) {
    // 设置日期选择器的起始日期为今天
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    this.setData({
      startDate: `${year}-${month}-${day}`
    });

    // 如果有传递的类型参数，设置为对应的类型
    if (options.type) {
      this.setData({
        publishType: options.type
      });
    }
  },

  // 选择发布类型
  selectType: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      publishType: type
    });
  },

  // 输入框变化处理
  onInputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 出发地选择
  onDepartureChange: function (e) {
    const index = e.detail.value;
    this.setData({
      departureIndex: index,
      'formData.departure': this.data.departureOptions[index]
    });
  },

  // 目的地选择
  onDestinationChange: function (e) {
    const index = e.detail.value;
    this.setData({
      destinationIndex: index,
      'formData.destination': this.data.destinationOptions[index]
    });
  },

  // 日期选择
  onDateChange: function (e) {
    this.setData({
      'formData.date': e.detail.value
    });
  },

  // 时间选择
  onTimeChange: function (e) {
    this.setData({
      'formData.time': e.detail.value
    });
  },

  // 表单验证
  validateForm: function () {
    const { formData } = this.data;

    if (!formData.departure) {
      wx.showToast({
        title: '请选择出发地',
        icon: 'none'
      });
      return false;
    }

    if (!formData.destination) {
      wx.showToast({
        title: '请选择目的地',
        icon: 'none'
      });
      return false;
    }

    if (!formData.date) {
      wx.showToast({
        title: '请选择日期',
        icon: 'none'
      });
      return false;
    }

    if (!formData.time) {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      });
      return false;
    }

    // 验证拼车时间不能早于当前时间
    const selectedDateTime = new Date(`${formData.date} ${formData.time}`);
    const now = new Date();
    if (selectedDateTime < now) {
      wx.showToast({
        title: '拼车时间不能早于当前时间',
        icon: 'none'
      });
      return false;
    }

    if (!formData.capacity || formData.capacity <= 0) {
      wx.showToast({
        title: '请输入有效的人数',
        icon: 'none'
      });
      return false;
    }

    if (!formData.price || formData.price < 0) {
      wx.showToast({
        title: '请输入有效的价格',
        icon: 'none'
      });
      return false;
    }

    if (!formData.contact.trim()) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交表单
  submitForm: function () {
    if (!this.validateForm()) {
      return;
    }

    wx.showLoading({
      title: '发布中...'
    });

    // 确保openid已获取
    this.ensureOpenid((openid) => {
      if (!openid) {
        wx.hideLoading();
        wx.showToast({
          title: '用户信息获取失败，请重新登录',
          icon: 'error'
        });
        return;
      }

      const db = wx.cloud.database();
      const carpoolData = {
        ...this.data.formData,
        type: this.data.publishType,
        createTime: new Date(),
        updateTime: new Date(),
        status: 'active' // active: 激活, inactive: 下架
      };

      db.collection('carpool').add({
        data: carpoolData
      }).then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });

        // 清空表单
        this.setData({
          departureIndex: -1,
          destinationIndex: -1,
          formData: {
            departure: '',
            destination: '',
            date: '',
            time: '',
            capacity: '',
            boardCapacity: '',
            price: '',
            contact: '',
            remark: ''
          }
        });

        // 延迟返回首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      }).catch(err => {
        console.error('发布失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '发布失败，请重试',
          icon: 'error'
        });
      });
    });
  },

  // 确保openid已获取
  ensureOpenid: function (callback) {
    const openid = wx.getStorageSync('openid');
    if (openid) {
      // openid 已存在，直接执行回调
      callback && callback(openid);
    } else {
      // openid 不存在，调用云函数获取
      wx.cloud.callFunction({
        name: 'init',
        success: res => {
          const openid = res.result.openid;
          wx.setStorageSync('openid', openid);
          callback && callback(openid);
        },
        fail: err => {
          console.error('获取openid失败', err);
          callback && callback(null);
        }
      });
    }
  }
});
